// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.FeeApportionObj;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.BdRateMapper;
import com.fowo.api.mapper.FeeApportionObjMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.model.bd.rate.BdRateItemVo;
import com.fowo.api.model.bd.rate.BdRateSearchParamPo;
import com.fowo.api.model.fee.apportion.obj.FeeApportionObjExcelPo;
import com.fowo.api.model.fee.apportion.obj.FeeApportionObjImportPo;
import com.fowo.api.model.fee.apportion.obj.FeeApportionObjItemVo;
import com.fowo.api.model.fee.apportion.obj.FeeApportionObjSearchParamPo;
import com.fowo.api.model.fee.apportion.obj.FeeApportionObjVo;
import com.fowo.api.model.fee.apportion.obj.constant.FeeApportionObjApportionTypeEnums;
import com.fowo.api.model.fee.apportion.obj.constant.FeeApportionObjXzEnums;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.service.FeeApportionObjService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 费用分摊对象 服务实现类
 * @author 蜂窝蜜造平台 配置人：李玉娇，王心成
 */
@Service
@Slf4j
@DS("ds24")
public class FeeApportionObjServiceImpl
  extends ServiceImpl<FeeApportionObjMapper, FeeApportionObj>
  implements FeeApportionObjService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("parentFeeManageCreateUser", "fm.`create_user`");
      put("nameName", "p.`name`");
      put("shopIdShopName", "si.`shop_name`");
      put("originalName", "br.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected BdRateMapper bdRateMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  private WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建费用分摊对象
   * @param model 费用分摊对象
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(FeeApportionObjVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FeeApportionObj entity = new FeeApportionObj();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getApportionType() == null) {
      entity.setApportionType("10");
    }

    if (model.getXz() == null) {
      entity.setXz("-1");
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("费用分摊对象保存失败");
  }

  /**
   * 批量更新 费用管理 下属数据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void saveAllByParentFeeManage(
    Long parentFeeManage,
    List<FeeApportionObjItemVo> list
  ) throws Exception {
    for (FeeApportionObjItemVo itemVo : list) {
      if (
        itemVo.getId() != null &&
        itemVo.getDelFlag() != null &&
        itemVo.getDelFlag()
      ) {
        // 删除处理
        this.delete(itemVo.getId());
        continue;
      }
      FeeApportionObj item = new FeeApportionObj();
      BeanUtils.copyProperties(itemVo, item);
      if (item.getParentFeeManage() == null) {
        item.setId(null);
        item.setParentFeeManage(parentFeeManage);
      }
      if (item.getId() == null) {
        this.save(item);
      } else {
        this.updateById(item);
      }
    }
  }

  /**
   * 更新费用分摊对象
   * @param model 费用分摊对象
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(FeeApportionObjVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FeeApportionObj entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("费用分摊对象不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新费用分摊对象（带空值）
   * @param model 费用分摊对象
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(FeeApportionObjVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FeeApportionObj entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("费用分摊对象不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(FeeApportionObj::getParentFeeManage, model.getParentFeeManage())
      .set(FeeApportionObj::getShopId, model.getShopId())
      .set(FeeApportionObj::getApportionType, model.getApportionType())
      .set(FeeApportionObj::getApportionDate, model.getApportionDate())
      .set(FeeApportionObj::getXz, model.getXz())
      .set(FeeApportionObj::getOriginalMoney, model.getOriginalMoney())
      .set(FeeApportionObj::getOriginal, model.getOriginal())
      .set(FeeApportionObj::getStandardCoinMoney, model.getStandardCoinMoney())
      .set(FeeApportionObj::getExchangeRate, model.getExchangeRate())
      .set(FeeApportionObj::getRemarks, model.getRemarks())
      .set(FeeApportionObj::getLastUpdateTime, model.getLastUpdateTime())
      .set(FeeApportionObj::getLastUpdateUser, model.getLastUpdateUser())
      .eq(FeeApportionObj::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(FeeApportionObjSearchParamPo search) {
    return false;
  }

  /**
   * 删除费用分摊对象
   * @param id 费用分摊对象的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除费用分摊对象
   * @param ids 费用分摊对象的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<FeeApportionObjImportPo> excelToImportRow(
    FeeApportionObjImportPo row,
    Integer rowNumber,
    FeeApportionObjVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<FeeApportionObjImportPo> ir =
      new ImportRow<FeeApportionObjImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<FeeApportionObjImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new FeeApportionObjVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, FeeApportionObjImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getApportionType())) {
      vo.setApportionType(
        FeeApportionObjApportionTypeEnums.toValue(row.getApportionType())
      );
      if (vo.getApportionType() == null) {
        ir.addError("apportionType", "分摊类型只能是：“按天”, “按月”");
      }
    }
    vo.setApportionDate(SheetUtils.tryToDate(row.getApportionDate()));
    SheetUtils.datePreviewFormat(row.getApportionDate(), row::setApportionDate);
    if (StringUtils.hasText(row.getFeeType())) {
      List<SysDictAllItem> feeTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "feeType",
          n -> sysDictService.getDictItems("SCM00098")
        );
      FeeApportionObjVo finalVo = vo;
      feeTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getFeeType()))
        .findFirst()
        .ifPresent(i -> finalVo.setFeeType(i.getItemValue()));
    }
    if (StringUtils.hasText(row.getXz())) {
      vo.setXz(FeeApportionObjXzEnums.toValue(row.getXz()));
      if (vo.getXz() == null) {
        ir.addError("xz", "支收选择只能是：“支出”, “收入”");
      }
    }
    vo.setOriginalMoney(SheetUtils.tryToDecimal(row.getOriginalMoney()));
    vo.setStandardCoinMoney(
      SheetUtils.tryToDecimal(row.getStandardCoinMoney())
    );
    // 处理关联字段“品名”
    if (
      !SheetUtils.isBlank(row.getNameName()) &&
      SheetUtils.isBlank(row.getName())
    ) {
      ProductSearchParamPo nameSearchParam = new ProductSearchParamPo();
      nameSearchParam.setLimit(2); // 最大只返回二行记录
      nameSearchParam.setNameEq(SheetUtils.trim(row.getNameName()));
      nameSearchParam.applySqlSegments();
      List<ProductItemVo> nameMatches = productMapper.search(nameSearchParam);
      if (nameMatches.size() == 0) {
        ir.addError("nameName", "未能在产品管理中找到匹配的数据");
      } else if (nameMatches.size() > 1) {
        ir.addError("nameName", "关联不唯一，在产品管理中找到多个匹配的数据");
      } else {
        vo.setName(nameMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", nameMatches.get(0).getId())
          .put("fromObjectName", "FeeApportionObj")
          .put("fromObjectId", vo.getId())
          .put("fromField", "name")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(2);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("sku")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("sku")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("sku")
              .rowFieldName("sku")
              .apiParams(apiParams)
              .required(true)
              .importIgnore(false)
              .build()
          );
        }
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("picUrl")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("picUrl")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("picUrl")
              .rowFieldName(null)
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(nameMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopIdShopName()) &&
      SheetUtils.isBlank(row.getShopId())
    ) {
      ShopInfoSearchParamPo shopIdSearchParam = new ShopInfoSearchParamPo();
      shopIdSearchParam.setLimit(2); // 最大只返回二行记录
      shopIdSearchParam.setShopNameEq(SheetUtils.trim(row.getShopIdShopName()));
      shopIdSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopIdMatches = shopInfoMapper.search(
        shopIdSearchParam
      );
      if (shopIdMatches.size() == 0) {
        ir.addError("shopIdShopName", "未能在店铺中找到匹配的数据");
      } else if (shopIdMatches.size() > 1) {
        ir.addError("shopIdShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setShopId(shopIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“原币”
    if (
      !SheetUtils.isBlank(row.getOriginalName()) &&
      SheetUtils.isBlank(row.getOriginal())
    ) {
      BdRateSearchParamPo originalSearchParam = new BdRateSearchParamPo();
      originalSearchParam.setLimit(2); // 最大只返回二行记录
      originalSearchParam.setNameEq(SheetUtils.trim(row.getOriginalName()));
      originalSearchParam.applySqlSegments();
      List<BdRateItemVo> originalMatches = bdRateMapper.search(
        originalSearchParam
      );
      if (originalMatches.size() == 0) {
        ir.addError("originalName", "未能在汇率中找到匹配的数据");
      } else if (originalMatches.size() > 1) {
        ir.addError("originalName", "关联不唯一，在汇率中找到多个匹配的数据");
      } else {
        vo.setOriginal(originalMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", originalMatches.get(0).getId())
          .put("fromObjectName", "FeeApportionObj")
          .put("fromObjectId", vo.getId())
          .put("fromField", "original")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(1);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains(
              "exchangeRate"
            )
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("rateNum")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("exchangeRate")
              .rowFieldName("exchangeRate")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(originalMatches),
          joinModels
        );
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<FeeApportionObjImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<FeeApportionObjImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            FeeApportionObjImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              FeeApportionObjImportPo row,
              AnalysisContext cxt
            ) {
              FeeApportionObjVo vo = new FeeApportionObjVo();
              ImportRow<FeeApportionObjImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<FeeApportionObjImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<FeeApportionObjImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      FeeApportionObjVo vo = new FeeApportionObjVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    FeeApportionObjSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "parentFeeManage",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((FeeApportionObjItemVo) r).getParentFeeManageCreateUser()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "shopId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((FeeApportionObjItemVo) r).getShopIdShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "apportionType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            FeeApportionObjApportionTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "apportionDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "feeType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00098")
      );
      exportOptions.addFieldMappingOption(
        "xz",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> FeeApportionObjXzEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "original",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((FeeApportionObjItemVo) r).getOriginalName())
          )
      );
      exportOptions.addStringFields(
        "shopIdShopName",
        "apportionType",
        "feeType",
        "xz",
        "originalName",
        "exchangeRate",
        "remarks"
      );

      String fileName = String.format(
        "费用分摊对象(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> feeTypeItems = sysDictService.getDictItems("SCM00098");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<FeeApportionObjExcelPo> items =
      new ArrayList<FeeApportionObjExcelPo>();
    while (true) {
      search.setCurrent(current);
      Page<FeeApportionObjItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<FeeApportionObjItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (FeeApportionObjItemVo item : list) {
        FeeApportionObjExcelPo excel = new FeeApportionObjExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setApportionType(
          FeeApportionObjApportionTypeEnums.toLabel(item.getApportionType())
        );
        if (item.getFeeType() != null) {
          feeTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getFeeType()))
            .findFirst()
            .ifPresent(i -> excel.setFeeType(i.getItemText()));
        }
        excel.setXz(FeeApportionObjXzEnums.toLabel(item.getXz()));

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "费用分摊对象(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(FeeApportionObjExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过SKU查询费用分摊对象主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdBySku(String sku) {
    return this.baseMapper.getIdBySku(sku);
  }

  /**
   * 通过SKU查询费用分摊对象多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsBySku(List<String> list) {
    return this.baseMapper.getIdsBySku(list);
  }

  /**
   * 通过费用分摊对象主键查询SKU
   */
  @Override
  public String getSkuById(Long id) {
    return this.baseMapper.getSkuById(id);
  }

  /**
   * 通过费用分摊对象主键查询SKU列表
   */
  @Override
  public List<String> getSkuByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getSkuByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("sku"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 费用分摊对象的主键
   */
  @Override
  public FeeApportionObjVo getVoById(Long id) throws Exception {
    FeeApportionObjVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询费用分摊对象
   * @param search 查询条件
   * @return 费用分摊对象分页查询结果
   */
  @Override
  public Page<FeeApportionObjItemVo> pageSearch(
    FeeApportionObjSearchParamPo search
  ) {
    Page<FeeApportionObjItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(FeeApportionObjItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 费用分摊对象快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'FeeApportionObjOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<FeeApportionObjItemVo>> searchOptions(
    FeeApportionObjSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询费用分摊对象
   * @param search 查询条件
   * @return 费用分摊对象列表查询结果
   */
  @Override
  public List<FeeApportionObjItemVo> search(
    FeeApportionObjSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询费用分摊对象最后更新时间
   * @param search 查询条件
   * @return 费用分摊对象最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(FeeApportionObjSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
